/**
 * 初始化整体流量图标
 */
define(function(){
    var ec=require('echarts');
    require('echarts/chart/line');
    require('echarts/chart/bar');

    var zrnumber = require('echarts/util/number');
    var zrUtil = require('zrender/tool/util');

    var myChart = ec.init(document.getElementById('trend'));
    var option_day = {

        tooltip : {
            trigger: 'axis',
                        formatter:tooltipFunc_1
        },
        legend: {
            data:[]
        },
        toolbox: {
            show : true,
            orient:'vertical',
            feature : {
                mark : {show: true},
                dataZoom : {show: true},
                magicType : {show: true, type: ['line', 'bar', 'stack', 'tiled']},
                restore : {show: true},
                saveAsImage : {show: true}
            }
        },
        calculable : true,
        xAxis: [{
            type: "category",
             boundaryGap: true,
            data:['']
        }],
        yAxis: [
            {
                type: 'value'
            }
        ],
        dataZoom: {
            show: true
        },
        series: []
    };

    var data_temp={
                name: '',
                type: 'line',
                smooth: true,
                symbol:"none",
                // stack: '总量',
                // itemStyle: {normal: {areaStyle: {type: 'default'}}},
                data:[]
            };


    function show(type,eventType){
        myChart.showLoading({
            text: '正在努力的读取数据中...'
        });
        var busiType=$("#busiTypeTrend").val();
        console.log(busiType);
        $.ajax({
            url: '/dashboard/income/ajax/getKpiByBusinessTrend',
            type: 'post',
            async: true,
            data:{"type":type,"busiType":busiType},
            dataType: 'json',
            success: function(data, textStatus) {
                // console.log(data);
                option_day.xAxis[0].data = data.time;
                option_day.legend.data=data.legend;
                option_day.series=[];
                $.each(data.data,function(index,value){
                    var ss=zrUtil.clone(data_temp);
                    ss.name=index;
                    ss.data=value;
                    option_day.series.push(ss);
                });
                               //区域缩放重置
                var datezoom_local={
                    day:{start:(1-31/data.time.length)*100,end:100},
                   month:{start:0,end:100},
                };

                if(data.time.length<31){
                    datezoom_local={
                        day:{start:0,end:100},
                        month:{start:0,end:100},
                    };
                }

                if(eventType == 1 || eventType == 2){
                    if('day'==type){
                        option_day.series.forEach(function(value){
                            value.type='line';
                        });
                    }else if('week_begin'==type){
                        option_day.series.forEach(function(value){
                            value.type='bar';
                        });
                    }else if('month'==type){
                        option_day.series.forEach(function(value){
                            value.type='bar';
                        });
                    }
                    if(eventType == 1 && myChart.component.dataZoom){
                        option_day.dataZoom=datezoom_local[type];
                        myChart.component.dataZoom.absoluteZoom(datezoom_local[type]);
                        option_day.dataZoom.show=true;
                    }else if(eventType == 2){
                        option_day.dataZoom=datezoom_local[type];
                        option_day.dataZoom.show=!$('#time_checkbox').is(":checked");
                    };
                    myChart.setOption(option_day,true);
                }else if(eventType == 0){
                    myChart.component.dataZoom=compDataZoom_old;
                    // option_day.dataZoom.show=true;
                    myChart.setOption(option_day,true);
                    if($('#time_input').val()){
                        addCompare($('#time_input').val());
                    }
                }
                myChart.hideLoading();
            },
            error : function() {
                myChart.hideLoading();
            }
        });
    }

        //时间勾选框事件
    $('#time_checkbox').change(function(e){
        var input=$('#time_input');
        if(!input)return;
        if($(this).is(":checked")){
            input.removeAttr('disabled');
            input.attr('placeholder','选择比较时间起点');               
            hideDataZoom();
            setDatePicker($('#trend_type').attr('dateGrp'),input);
        }else{
            input.val('');
            input.attr('disabled','');
            input.attr('placeholder','添加对比');               
            removeCompare();
        }
    });

        var datepicker_op={
        format: "yyyy-mm-dd",
        clearBtn: false,
        language: "zh-CN",
        autoclose: true,
        todayHighlight: true,
        minViewMode:0,
        orientation: "top left"
    };

        function setDatePicker(dateGrp,input){
        if('day'==dateGrp){
            datepicker_op.minViewMode=0;
            datepicker_op.format='yyyy-mm-dd';
        }else if('month'==dateGrp){
            datepicker_op.minViewMode=1;
            datepicker_op.format='yyyymm';
        }
        input.datepicker('remove');
        input.datepicker(datepicker_op);
        //获取显示的日期数组
        var days_show=getShowDays();
        var days_all=getAllDays();
        //设置时间可选范围
        input.datepicker('setStartDate',new Date(getDate(days_all[0])));
        input.datepicker('setEndDate',new Date(getDate(days_all[days_all.length-days_show.length])));
    }

    function getDate(yyyymmdd){
        if(yyyymmdd.length==6){
            return Date.parse(yyyymmdd.substr(0,4)+'-'+yyyymmdd.substr(4,2));
        }
        return yyyymmdd;
    }

        function getShowDays(){
        return compDataZoom_old.option.xAxis[0].data;
    }

    function getAllDays(){
        return option_day.xAxis.data||option_day.xAxis[0].data;
    }

        function addCompare(time){
        var copy=zrUtil.clone(option_day);
        copy.toolbox.feature.magicType.show=false;
        copy.toolbox.feature.dataZoom.show=false;
        var index_time=getIndexByName(option_day.xAxis[0].data,time);
        var index_show=getIndexByName(option_day.xAxis[0].data,getShowDays()[0]);
        var length=getShowDays().length;
        setCompareXaxis(copy,index_time,index_show,length);
        var index=0;
        //选中对比时，再次选择指标，需要记忆图例的选择状态
        $.each(legend_SelectedMap,function(key,value){
            //判断是否在当前图例值中，应为echarts会把"对比时间段"也放入SelectedMap
            if($.inArray(key,option_day.legend.data) != -1){
                if(value){
                    return false;
                }
                index++;
            }     
        });
        // console.log(index);

            setCompareSeries(copy,index,index_time,index_show,length);
            setCompareLegend(copy);
            setCompareTooltip(copy);
            delete copy.dataZoom;
            myChart.restore();
            myChart.setOption(copy,true);


    }

    var compDataZoom_old;
    var legend_SelectedMap={};  //需要记忆图例的选择状态
    function hideDataZoom(){
        legend_SelectedMap=myChart.component.legend.getSelectedMap();
        compDataZoom_old=myChart.component.dataZoom;    //记忆缩放
        option_day.dataZoom.show=false;
        myChart.setOption(option_day,false);
    }

    function removeCompare(){
        //恢复缩放
        myChart.component.dataZoom=compDataZoom_old;
        option_day.dataZoom.show=true;
        //去掉对比时恢复图例的选择状态
        $.each(legend_SelectedMap,function(key,value){
            if($.inArray(key,option_day.legend.data) != -1){
                myChart.component.legend.setSelected(key,value);
            }else{
                myChart.component.legend.setSelected(key,false);
            }
        });
        myChart.setOption(option_day,true);
    }


    function setCompareTooltip(copy){
        copy.series[1]&&copy.series[1].tooltip&&(copy.series[1].tooltip={show:false});
        copy.series[2]&&copy.series[2].tooltip&&(copy.series[2].tooltip={show:false});
        copy.series[3]&&copy.series[3].tooltip&&(copy.series[3].tooltip={show:false});

        copy.tooltip.formatter=function(params, ticket, callback){
            var date_current=params[0][1];
            var data_current=params[0][2];
            var index_current=getIndexByName(copy.xAxis[0].data,date_current);

            var dateVal = formatShowDate(date_current);
            var result='<table class="table-center">' +
                '<tr><td>'+dateVal;
            //是日要显示周几
            if(isDay())
                 result += ' ('+getWeekDay(dateVal)+')';
            result += '</td><td>'+zrnumber.addCommas(data_current)+'</td></tr>';
            if(copy.series[1]){
                var data_compare=copy.series[1].data[index_current];
                var s=(((data_current-data_compare)/data_compare)*100).toFixed(2);
                dateVal = formatShowDate(copy.xAxis[1].data[index_current]);
                result+='<tr><td>'+dateVal;
                if(isDay())
                    result += ' ('+getWeekDay(dateVal)+')';
                result += '</td><td>'+zrnumber.addCommas(data_compare)+'</td></tr>';
                if(s>0){
                    result+='<tr><td>变化</td><td style="color: orangered">'+s+'%&#8593</td></tr>';
                }else{
                    result+='<tr><td>变化</td><td style="color: greenyellow">'+s+'%&#8595</td></tr>';
                }
            }
            result+='</table>';
            return   result;
        }
    }

    function setCompareLegend(copy){
        copy.legend= {
            data:[copy.series[0].name, copy.series[1].name],
            selectedMode:false
        }
    }

    function  setCompareSeries(copy,index,index_time,index_show,length){
        copy.series=[];
        //原来数据
        copy.series.push(zrUtil.clone(option_day.series[index]));
        copy.series[0].type='line';
        copy.series[0].data=option_day.series[index].data.slice(index_show,index_show+length);
        delete  copy.series[0].stack;
        delete  copy.series[0].itemStyle;
        //对比数据
        copy.series.push(zrUtil.clone(option_day.series[index]));
        copy.series[1].type='line';
        copy.series[1].name="对比时间段";
        copy.series[1].xAxisIndex=1;
        delete  copy.series[1].stack;
        delete  copy.series[1].itemStyle;

        copy.series[1].data=option_day.series[index].data.slice(index_time,index_time+length);
        if(length>31){return}
        //对比柱
        copy.series.push({
            tooltip:{show:false},
            show:false,
            name: '对比时间段1',
            type: 'bar',
            stack: '1',
            barWidth:3,
            xAxisIndex:1,
            itemStyle:{
                normal:{
                    color:'rgba(0,0,0,0)'
                },
                emphasis:{
                    color:'rgba(0,0,0,0)'
                }
            },
            data: function(){
                var i=0;
                return $.map(copy.series[1].data,function(val){
                    var tt=copy.series[0].data[i++];
                    if(val<tt){
                        return val;
                    }else{
                        return tt;
                    }
                })
            }()
        });
        copy.series.push({
            tooltip:{show:false},
            name: '变化',
            type: 'bar',
            stack: '1',
            xAxisIndex:1,
            data: function(){
                var i=0;
                return $.map(copy.series[1].data,function(val){
                    var tt=copy.series[0].data[i++];
                    if(val<tt){
                        return tt-val;
                    }else{
                        return {value : val-tt, itemStyle:{ normal:{color:'red'}}};
                        //return val-tt;
                    }
                })
            }()
        });
    }

    function setCompareXaxis(copy,index_time,index_show,length){
        copy.xAxis=[];
        copy.xAxis.push(zrUtil.clone(option_day.xAxis[0]));
        copy.xAxis.push(zrUtil.clone(option_day.xAxis[0]));
        copy.xAxis[0].data=option_day.xAxis[0].data.slice(index_show,index_show+length);
        copy.xAxis[1].data=option_day.xAxis[0].data.slice(index_time,index_time+length);
    }

        function getIndexByName(data,name) {
        var dataLength = data.length;
        for (var i = 0; i < dataLength; i++) {
            if (data[i] == name || typeof data[i].value != 'undefined' && data[i].value == name) {
                return i;
            }
        }
        return -1;
    }
    function formatTime(time){
        return time.replace(/\-/g,'')
    }

        function formatShowDate(yyyymmdd){
        return yyyymmdd;
    }

        //时间选择事件
    $('#time_input').datepicker().on('changeDate',function(e){
        addCompare(e.format());
    });

        function isDay(){
        var dateGrp = $('#trend_type').attr('dateGrp');
        if('day'==dateGrp){
            return true;
        }
        return false;
    }

    function isWeek(){
        return false;
    }

    function isMonth(){
        var dateGrp = $('#trend_type').attr('dateGrp');
        if('month'==dateGrp){
            return true;
        }
        return false;
    }

var dayMap={1:"周一",2:"周二",3:"周三",4:"周四",5:"周五",6:"周六",0:"周日"};
        function getWeekDay(dayDate){
        var jsDate = new Date(Date.parse(dayDate));
        var weekNumber = jsDate.getDay();
        return dayMap[weekNumber];
    }

        function tooltipFunc_1(params, ticket, callback){
        return tooltipFunc(params, ticket, callback,1);
    }
    function  tooltipFunc(params, ticket, callback,showType){
        var dateVal = formatShowDate(params[0].name);
        var index_current=getIndexByName(option_day.xAxis[0].data,params[0].name);

        var result='<table class="table-center">';
        result+='<tr><td>'+dateVal+'</td><td>';
        var isStatDay = isDay(); 
        if(isStatDay)
            result += getWeekDay(dateVal);
        result += '</td>';
        if(showType == 1){
             result += '</td><td>占比</td>';
        }
        if(isStatDay)
            result +="<td>日环比</td><td>周同比</td>";
        else if(isWeek())
            result += "<td>周环比</td>";
         else if(isMonth())
            result += "<td>月同比</td>";
        result += '</tr>';
        var total=0;
        if(showType == 1){
            $(params).each(function(index,para){
                total+=para.data;
            });
        }

        $(params).each(function(index,para){
            result+='<tr><td>'+para.seriesName+'</td><td>'+zrnumber.addCommas(para.data)+'</td>';
            if(showType == 1){
                 var s = ((para.data/total)*100).toFixed(2);
                 result+='<td>'+s+'%</td>';
            }
           
            var seriesIndex = para.seriesIndex;
            var day_td="<td>无</td>";
            //环比
            if(index_current-1>=0){
                var data_yesday = null;
                //去年同月
                if(isMonth()){
                    if(index_current-12>=0){
                        data_yesday= option_day.series[seriesIndex].data[index_current-12];
                    }
                }else{ 
                    data_yesday= option_day.series[seriesIndex].data[index_current-1];                
                }
                if(data_yesday != null){
                    var s=(((para.data/data_yesday)-1)*100).toFixed(2);
                    if(s>0){
                        day_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                    }else{
                        day_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                    }
                }
            }
            result += day_td;
            //周同比
            if(isStatDay){
                var week_td='<td>--</td>';
                if(index_current-7>=0){
                    data_week= option_day.series[seriesIndex].data[index_current-7];
                    var s=(((para.data/data_week)-1)*100).toFixed(2);
                    if(s>0){
                        week_td='<td style="color: orangered;">'+s+'%&#8593</td>';
                    }else{
                        week_td='<td style="color: greenyellow;">'+s+'%&#8595</td>';
                    }
                }
                result += week_td;
            }
            result += '</tr>';
        });
        result+='</table>';
        return result;
    }  


    var obj={
        show:show
    };

    return obj;
});

